<script lang="ts">
	import { Tooltip } from 'flowbite-svelte'
	import type { KlineFlat, Klt } from './bindings'
	import { derived, writable, type Unsubscriber } from 'svelte/store'
	import {
		Table,
		TableBody,
		TableBodyCell,
		TableBodyRow,
		TableHead,
		TableHeadCell,
	} from 'flowbite-svelte'
	import { onDestroy, onMount, tick } from 'svelte'
	import ColoredValue from './ColoredValue.svelte'

	import {
		klineRequestStore,
		klineResultStore,
		klineTableConfStore,
		updateKlineRequest,
	} from './FudaStore'
	import { format_datetime } from '$lib'
	// 使用 $: 响应式声明来更新 sliderState
	$: klineResultState = $klineResultStore
	$: klineTableConfState = $klineTableConfStore
	let klines: KlineFlat[] = []
	$: {
		klines = $klineResultStore.klines
		console.log('(KlineTable.svelte) updated klines', klineResultState.klines)
	}

	export let klt: Klt
	let limit = 15 // 只显示前15项
	const buttonTextStore = writable('Show All')

	let subscription: Unsubscriber
	const lastKnownStateStore = writable({ value: 0, loading: false, valueUpdated: false })

	onMount(async () => {
		console.log(`(KlineTable) onMount with klts:, klt=${klt}, `)

		updateKlineRequest(null, klt, 0, null)

		subscription = klineRequestStore.subscribe(async (state) => {
			limit = 15
			buttonTextStore.set('Show All')
		})
	})

	onDestroy(() => {
		if (subscription) {
			// 销毁订阅
			subscription()
		}
	})

	const buttonText = derived(buttonTextStore, ($buttonTextStore) => $buttonTextStore)

	async function showAll() {
		buttonTextStore.set('Show All In Progress ...')

		// 等待Svelte的下一个tick，确保DOM更新
		await new Promise((resolve) => setTimeout(resolve, 0))

		// 进行异步操作，例如更新limit
		limit = klines.length

		// 更新按钮文本为默认值，或者你想要的任何值
		buttonTextStore.set('Show All')

		// 再次等待Svelte的下一个tick，确保DOM更新
		await new Promise((resolve) => setTimeout(resolve, 0))
	}
</script>

<Table hoverable={true}>
	<TableHead defaultRow={false}>
		<tr
			class="bg-gray-400 text-center text-xs font-medium text-gray-900 uppercase sticky top-0 z-10"
		>
			<TableHeadCell padding="pr-2" class="text-nowrap sticky left-0 top-0 bg-gray-400">
				日期<br />时间
			</TableHeadCell>
			<TableHeadCell padding="pr-2" class="text-nowrap">开盘价<br />O</TableHeadCell>
			<Tooltip arrow={false} placement="top">Signal</Tooltip>
			<TableHeadCell padding="pr-2" class="text-nowrap">最高价<br />H</TableHeadCell>
			<Tooltip arrow={false} placement="top">Signal</Tooltip>
			<TableHeadCell padding="pr-2" class="text-nowrap">最低价<br />L</TableHeadCell>
			<Tooltip arrow={false} placement="top">Signal</Tooltip>
			<TableHeadCell padding="pr-2" class="text-nowrap">收盘价<br />C</TableHeadCell>
			<TableHeadCell padding="pr-2" class="text-nowrap">成交量<br />V</TableHeadCell>
			<TableHeadCell padding="pr-2" class="text-nowrap">指标<br />评分</TableHeadCell>

			{#if klineTableConfState.klineTableConf && klineTableConfState.klineTableConf.columns && klineTableConfState.klineTableConf.columns.length > 0}
				<!-- Add a guard clause -->
				{#each klineTableConfState.klineTableConf.columns as column, index (column.id)}
					{#if column.visible && column.visible === true}
						<TableHeadCell padding="pr-2" class="text-wrap">{column.title}</TableHeadCell>
					{/if}
				{/each}
			{/if}
		</tr>
	</TableHead>
	<TableBody tableBodyClass="divide divide-solid divide-green-200 text-xs text-gray-500">
		{#each klines.slice(0, limit) as kline, index (kline.id)}
			<TableBodyRow class="divide-x divide-slate-200 hover:bg-green-400">
				<TableBodyCell
					tdClass="pr-1"
					class="text-xs font-medium text-gray-900 whitespace-nowrap sticky left-0 bg-gray-200 hover:bg-green-400"
				>
					{format_datetime(index.toString().padStart(3, '0'), kline.klts, klt)}
				</TableBodyCell>
				<TableBodyCell tdClass="pr-1">{kline.open}</TableBodyCell>
				<TableBodyCell tdClass="pr-1">{kline.high}</TableBodyCell>
				<TableBodyCell tdClass="pr-1">{kline.low}</TableBodyCell>
				<TableBodyCell tdClass="pr-1">{kline.close}</TableBodyCell>
				<TableBodyCell tdClass="pr-1">{kline.volume}</TableBodyCell>
				<TableBodyCell tdClass="pr-1">888.99</TableBodyCell>

				{#if klineTableConfState.klineTableConf && klineTableConfState.klineTableConf.columns && klineTableConfState.klineTableConf.columns.length > 0}
					<!-- Add a guard clause -->
					{#each klineTableConfState.klineTableConf.columns as column, index (column.id)}
						{#if column.visible && column.visible === true}
							<TableBodyCell tdClass="pr-1">
								<ColoredValue klineFlat={kline} columnName={column.name} />
							</TableBodyCell>
						{/if}
					{/each}
				{/if}
			</TableBodyRow>
		{/each}
		<TableBodyRow>
			<TableBodyCell colspan="8">
				{#if limit < klineResultState.klines.length}
					<button
						class="border border-solid bg-blue-400 text-white w-full h-12 rounded-md"
						on:click={() => showAll()}
					>
						{$buttonText}
					</button>
				{:else}
					Bottom Line
				{/if}
			</TableBodyCell>
		</TableBodyRow>
	</TableBody>
</Table>
